package com.bdtop.dbl.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;

import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.utils.DiskLruCache.Snapshot;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/** 
 * 异步下载图片的任务。 双缓存
 */  
public class BitmapWorkerTask extends AsyncTask<Object, Void, Bitmap> {

	/** 
	 * 图片的URL地址 
	 */  
	private String imageUrl;
	private ImageView imageView;
	private DiskLruCache mDiskLruCache;
	private LruCache<String, Bitmap> mMemoryCache;

	@SuppressWarnings("unchecked")
	@Override  
	protected Bitmap doInBackground(Object... params) {  
		imageUrl = params[0].toString();
		imageView= (ImageView) params[1];
		mDiskLruCache= (DiskLruCache) params[2];
		mMemoryCache=(LruCache<String, Bitmap>) params[3];
		
		FileDescriptor fileDescriptor = null;  
		FileInputStream fileInputStream = null;  
		Snapshot snapShot = null;  
		try {  
			// 生成图片URL对应的key  
			final String key =mDiskLruCache.hashKeyForDisk(imageUrl);  
			// 查找key对应的缓存  
			snapShot = mDiskLruCache.get(key);
			if (snapShot == null) {  
				// 如果没有找到对应的缓存，则准备从网络上请求数据，并写入缓存  
				DiskLruCache.Editor editor = mDiskLruCache.edit(key);  
				if (editor != null) {  
					OutputStream outputStream = editor.newOutputStream(0);  
					if (downloadUrlToStream(imageUrl, outputStream)) {  
						editor.commit();  
					} else {
						editor.abort();
					}  
				}  
				// 缓存被写入后，再次查找key对应的缓存  
				snapShot = mDiskLruCache.get(key);  
			}  
			if (snapShot != null) {  
				fileInputStream = (FileInputStream) snapShot.getInputStream(0);  
				fileDescriptor = fileInputStream.getFD();  
			}  
			// 将缓存数据解析成Bitmap对象  
			Bitmap bitmap = null;  
//			if (fileDescriptor != null) {  
//				bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);  
//			}
			int reqWidth = ScreenUtil.getScreenWidth(DBLApplication.getInstance());
			bitmap = ImageUtils.decodeStream(fileInputStream, reqWidth, 99999999);
			
			if (bitmap != null) {  
				// 将Bitmap对象添加到内存缓存当中  
				//addBitmapToMemoryCache(params[0].toString(), bitmap); 
				if(null==mMemoryCache.get(params[0].toString())){
					mMemoryCache.put(params[0].toString(), bitmap);
				}
			}
			return bitmap;  
		} catch (IOException e) {  
			e.printStackTrace();  
		} finally {  
			if (fileDescriptor == null && fileInputStream != null) {  
				try {  
					fileInputStream.close();  
				} catch (IOException e) {  
				}  
			}  
		}  
		return null;  
	}  

	@Override  
	protected void onPostExecute(Bitmap bitmap) {  
		super.onPostExecute(bitmap);  
		// 根据Tag找到相应的ImageView控件，将下载好的图片显示出来。  
		//ImageView imageView = (ImageView) mPhotoWall.findViewWithTag(imageUrl);  
		if (imageView != null && bitmap != null) {
			imageView.setImageBitmap(bitmap);
		}  
	}  

	/** 
	 * 建立HTTP请求，并获取Bitmap对象。 
	 *  
	 * @param imageUrl 
	 *            图片的URL地址 
	 * @return 解析后的Bitmap对象 
	 */  
	private boolean downloadUrlToStream(String urlString, OutputStream outputStream) {  
		HttpURLConnection urlConnection = null;  
		BufferedOutputStream out = null;  
		BufferedInputStream in = null;  
		try {  
			final URL url = new URL(urlString);  
			urlConnection = (HttpURLConnection) url.openConnection();  
			in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);  
			out = new BufferedOutputStream(outputStream, 8 * 1024);  
			int b;  
			while ((b = in.read()) != -1) {  
				out.write(b);  
			}  
			return true;  
		} catch (final IOException e) {  
			e.printStackTrace();  
		} finally {  
			if (urlConnection != null) {  
				urlConnection.disconnect();  
			}  
			try {  
				if (out != null) {  
					out.close();  
				}  
				if (in != null) {  
					in.close();  
				}  
			} catch (final IOException e) {  
				e.printStackTrace();  
			}  
		}  
		return false;  
	}  
}
